
<template>
    <image v-if="value" mode="aspectFill" :style="customStyle" class="show" @tap="click"
        :src="api.HOST + '?sjdx.dxdm=SYS_QX_QTQX&sys.cllx=download&yobj.id=' + value">
    </image>
    <view class="add" v-else-if="update" @tap="click">
        <uni-icons type="plusempty" size="30" style="color: #666666;"></uni-icons>
    </view>
    <view v-else>
        暂无图片
    </view>
</template>
<script setup lang="ts">
import { uploadFile } from '@/utils/net';
import api from '@/utils/net/api';
import { ref, watch } from 'vue';
const props = defineProps({
    modelValue: {
        type: String,
    },
    update: {
        type: Boolean,
        default: false
    },
    customStyle: {
        type: String,
    }
})
const value = ref("")
const emits = defineEmits(['update:modelValue']);
if (props.modelValue) {
    value.value = props.modelValue
}

watch(() => props.modelValue, (newValue) => {
    if (newValue) {
        if (props.modelValue) {
            value.value = newValue
        }
    }
})
const click = () => {
    if (props.update) {
        upload()
    } else {
        preview()
    }
}
const preview = () => {
    if (props.modelValue) {
        uni.previewImage(
            { current: 0, urls: [api.HOST + '?sjdx.dxdm=SYS_QX_QTQX&sys.cllx=download&yobj.id=' + props.modelValue] }
        )
    }
}
const upload = () => {
    uni.chooseImage({
        count: 1, //默认9
        sizeType: ['original', 'compressed'], //可以指定是原图还是压缩图，默认二者都有
        sourceType: ['album'], //从相册选择
        success: function (res) {
            console.log(res)
            const file = res.tempFiles[0], isLt2M = file.size / 1024 / 1024 < 2;
            if (!isLt2M) {
                uni.showToast({
                    title: '上传图片不能大于2M',
                    icon: 'none'
                })
                return;
            }
            uploadFile(file).then((result) => {
                if (result.data.status) {
                    uni.showToast({
                        title: '上传成功'
                    })
                    value.value = result.data.data[0].id
                    emits('update:modelValue', result.data.data[0].id)
                }
                console.log(result);
            })
        }
    });
}
</script>
<style lang="scss" scoped>
.show {
    width: 100rpx;
    height: 100rpx;
    border-radius: 8rpx;
}

.add {
    display: flex;
    align-items: center;
    justify-content: center;
    width: 100rpx;
    height: 100rpx;
    border-radius: 8rpx;
    border: 1px solid #f0f0f0;
}
</style>
